/*
 * Copyright (C) 2019 ByteDance Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bytedance.scene.dialog.alert;

import com.bytedance.scene.Scene;
import com.bytedance.scene.dialog.DialogScene;
import com.bytedance.scene.navigation.NavigationScene;
import com.bytedance.scene.navigation.NavigationSceneGetter;
import com.bytedance.scene.navigation.OnBackPressedListener;
import ohos.aafwk.ability.Lifecycle;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.StackLayout;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

public class AlertDialogScene extends DialogScene implements IDialog.ClickedListener,CannelDialog {
    static final int LAYOUT_HINT_NONE = 0;
    static final int LAYOUT_HINT_SIDE = 1;
    private boolean mShowing = false;
    private AlertController mAlert;
    private StackLayout mFrameRootLayout;
    private boolean mCancelable = true;
    private AlertDialogScene.Builder builder;
    private boolean mCanceledOnTouchOutside = false;
    private boolean mCanceled = false;
    private EventRunner mDismissMessage;
    private StackLayout mFrameContainer;
    private final Runnable mDismissAction = new Runnable() {
        @Override public void run() {
            dismissDialog();
        }
    };
    EventRunner runner = EventRunner.create(false);
    private final EventHandler mHandler = new EventHandler(runner);
    @Override
    public Component onCreateView(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        initRootView();
        Component child = onCreateContentView(scatter, container, intent);
        StackLayout.LayoutConfig layoutParams = new  StackLayout.LayoutConfig(
               ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT);
        layoutParams.alignment = LayoutAlignment.CENTER;
        StackLayout.LayoutConfig layoutParams2 = new  StackLayout.LayoutConfig(
               ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
        mFrameRootLayout.setLayoutConfig(layoutParams2);
        Display display = DisplayManager.getInstance().getDefaultDisplay(requireActivity()).get();
        int width = display.getAttributes().width;
        int height = display.getAttributes().height;
        StackLayout.LayoutConfig layoutParams3 = new  StackLayout.LayoutConfig(width-100,height/5);
        layoutParams3.alignment = LayoutAlignment.CENTER;
        if (mFrameContainer != null) {
            mFrameContainer.addComponent(child, layoutParams3);
            mFrameRootLayout.addComponent(mFrameContainer, layoutParams);
        } else {
            mFrameRootLayout.addComponent(child, layoutParams3);
        }
        return mFrameRootLayout;
    }

    private void initRootView() {
        mFrameRootLayout = new StackLayout(requireActivity());
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(RgbColor.fromArgbInt(0x99000000));
        mFrameRootLayout.setBackground(shapeElement);

        Component cptClick=new Component(requireSceneContext());
        cptClick.setClickedListener(component -> {
            if (mCanceledOnTouchOutside) {
                if(AlertDialogScene.this.getApplicationContext()!=null){
                    NavigationSceneGetter.requireNavigationScene(AlertDialogScene.this).pop();
                }
            }
        });
        mFrameRootLayout.addComponent(cptClick,new StackLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT));
    }

    @Override
    public void onViewCreated(Component component, Intent intent) {
        super.onViewCreated(component, intent);
        mShowing = true;
        NavigationSceneGetter.requireNavigationScene(this).addOnBackPressedListener(this, new OnBackPressedListener() {
            @Override
            public boolean onBackPressed() {
                return !mCancelable;
            }
        });
    }
    public void setCanceledOnTouchOutside(boolean cancel) {
        if (cancel && !mCancelable) {
            mCancelable = true;
        }
        mCanceledOnTouchOutside = cancel;
    }
    protected Component onCreateContentView(LayoutScatter layoutScatter, ComponentContainer container, Intent intent){
        this.mAlert = new AlertController(requireSceneContext(), this, getActivity().getWindow());
        int resId = this.mAlert.installContent();
        Component view = layoutScatter.parse(resId, container, false);
        this.mAlert.setupView(view);
        this.builder.P.apply(mAlert,this);
        mFrameContainer = new StackLayout(requireSceneContext());
        return view;
    }
    void dismissDialog() {
        if (!mShowing) {
            return;
        }
        if (getLifecycle().getLifecycleState() == Lifecycle.Event.ON_STOP) {
            return;
        }
        NavigationSceneGetter.requireNavigationScene(AlertDialogScene.this).pop();
        System.out.println("关闭scene!");
        mShowing = false;
    }

    private void sendDismissMessage() {
        if (mDismissMessage != null) {
        }
    }


    public void cancel() {
        dismiss();
    }


    public void dismiss() {
        dismissDialog();
    }


    public static AlertDialogScene create(AlertDialogScene.Builder builder) {
        AlertDialogScene scene = new AlertDialogScene();
        scene.builder = builder;
        scene.setCancelable(builder.P.mCancelable);
        if (builder.P.mCancelable) {
            scene.setCanceledOnTouchOutside(true);
        }
        return scene;
    }

    @Override
    public void onClick(IDialog iDialog, int i) {

    }

    @Override
    public void dissmissDialog() {
        dismiss();
    }

    public static class Builder {
        private AlertController.AlertParams P = null;
        private Scene hostScene = null;

        public Builder(Scene hostScene) {
            this(hostScene,
                    0);
        }
        public Builder( Scene hostScene, int themeResId) {
            this.hostScene = hostScene;
            Context context = hostScene.requireSceneContext();
            this.P = new AlertController.AlertParams(context);
        }

        public Context getContext() {
            return this.P.mContext;
        }

        public AlertDialogScene.Builder setTitle(CharSequence title) {
            this.P.mTitle = title;
            return this;
        }

        public AlertDialogScene.Builder setMessage( CharSequence message) {
            this.P.mMessage = message;
            return this;
        }
        public AlertDialogScene.Builder setPositiveButton(CharSequence text, DialogInterface listener) {
            this.P.mPositiveButtonText = text;
            this.P.mPositiveButtonListener = listener;
            return this;
        }
        public AlertDialogScene.Builder setNegativeButton(CharSequence text,  DialogInterface listener) {
            this.P.mNegativeButtonText = text;
            this.P.mNegativeButtonListener = listener;
            return this;
        }
        public AlertDialogScene.Builder setNeutralButton(CharSequence text, DialogInterface listener) {
            this.P.mNeutralButtonText = text;
            this.P.mNeutralButtonListener = listener;
            return this;
        }

        public AlertDialogScene.Builder setView(int layoutResId) {
            this.P.mView = null;
            this.P.mViewLayoutResId = layoutResId;
            this.P.mViewSpacingSpecified = false;
            return this;
        }
        public AlertDialogScene.Builder setView(Component view, int viewSpacingLeft, int viewSpacingTop, int viewSpacingRight, int viewSpacingBottom) {
            this.P.mView = view;
            this.P.mViewLayoutResId = 0;
            this.P.mViewSpacingSpecified = true;
            this.P.mViewSpacingLeft = viewSpacingLeft;
            this.P.mViewSpacingTop = viewSpacingTop;
            this.P.mViewSpacingRight = viewSpacingRight;
            this.P.mViewSpacingBottom = viewSpacingBottom;
            return this;
        }
        public AlertDialogScene create() {
            AlertDialogScene.Builder builder = this;
            AlertDialogScene scene = new AlertDialogScene();
            scene.builder = builder;
            scene.setCancelable(builder.P.mCancelable);
            if (builder.P.mCancelable) {
                scene.setCanceledOnTouchOutside(true);
            }
            return scene;
        }

        public AlertDialogScene show() {
            AlertDialogScene scene = create();
            scene.show(hostScene);
            return scene;
        }
    }
    public void setCancelable(boolean cancelable) {
        mCancelable = cancelable;
    }
}
